package com.sky.spring.dao.impl;

import com.alibaba.druid.pool.DruidPooledConnection;
import com.sky.spring.dao.AccountDao;
import com.sky.spring.pojo.Account;
import com.sky.spring.utils.ConnectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * Description:
 *
 * @author Sky
 * @Date 2021/7/30 12:57
 */
/*@Component("accountDao")*/
// @Repository（通常定义在在dao层） 为@Component 的别名为了更加清晰分区
@Repository("accountDao")
public class AccountDaoImpl implements AccountDao {

   // @Autowired 按类型注入。去Spring容器找 ConnectionUtils 的类，然后将其注入进来。
    @Autowired
    private ConnectionUtils connectionUtils;


    // 在接口 实现类中 实现根据 cardNo查询账户的方法
    @Override
    public Account queryAccountCardNo(String cardNo) throws SQLException, Exception {
       // DruidPooledConnection connection = DruidUtils.getInstance().getConnection();
        Connection connection = connectionUtils.getCurrentThreadConn();
        System.out.println(" queryAccountCardNo connection: " +connection);
        String sql = "select * from account where cardNo = ?";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);

        preparedStatement.setString(1,cardNo);

        ResultSet resultSet = preparedStatement.executeQuery();

        Account account = new Account();

        while (resultSet.next()){

            account.setMoney(resultSet.getInt("money"));
            account.setCardNo(resultSet.getString("cardNo"));
            account.setName(resultSet.getString("name"));

        }

        resultSet.close();
        preparedStatement.close();
      // connection.close();

        return  account;
    }
    // 在接口 实现类中 实现 根据 cardNo 修改 money 的方法
    @Override
    public int updateAccountByCardNo(Account account) throws Exception {

       // DruidPooledConnection connection = DruidUtils.getInstance().getConnection();
        Connection connection = connectionUtils.getCurrentThreadConn();
        System.out.println(" updateAccountByCardNo connection: " +connection);
        String sql = "update account set money = ? where cardNo = ?";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);

        preparedStatement.setInt(1,account.getMoney());
        preparedStatement.setString(2,account.getCardNo());

        int i = preparedStatement.executeUpdate();

        preparedStatement.close();
      // connection.close();

        return i;
    }
}
